import 'server-only' //代表仅服务端可用 
import resFn from '@/app/api/util/res'
import { NextRequest } from 'next/server';
import { logError } from '@/app/api/util/io/log';
import { getBody, judge, permissionJudge } from '@/app/api/util/res/handle';
import { DeleteFileReq } from '@/types/api/file/deleteFile';
import { stringJoi } from '@/app/api/util/Joi';
import { ResCode, RejectData } from '@/app/api/util/res/code';
import { getFileUser, publicToServerPath } from '../getPath';
import { deleteFile } from '@/app/api/util/io';
export const dynamic = 'force-dynamic';

/**用户删除自己上传的文件 接口*/
export async function POST(request: NextRequest) {
    try {
        const user_id = "JZ8740"
        const { filePath } = await judge(await getBody<DeleteFileReq>(request), { filePath: stringJoi() })
        //目标：拆解字符串"https://aigc.yy.com/public_resource/get_data//other/JZ8322_7950ffb27039e6cc08921b32dbbea59a.svg"
        const fileUser = getFileUser(filePath)
        if (fileUser !== user_id) throw new RejectData(ResCode.FORBIDDEN, '无权限删除')
        const serverPath = publicToServerPath(filePath)
        try {
            await deleteFile(serverPath)
            return resFn.success<any>("操作成功");
        } catch (error) {
            throw new RejectData(ResCode.BAD_REQUEST, '当前文件已被删除')
        }
    } catch (error: any) {
        logError('用户删除自己上传的文件 接口', error)
        return resFn.errorWithReject(error);
    }
}

